<?php
	include 'session.inc';
	include 'createFileName.inc';
	check_login();
	
	function createBlogPost($fileName, $title, $text, $imgPath) {
		$fp = fopen($fileName, 'w');
		if(!$fp) {
			print 'Error creating blog post';
			return 0;
		}
		else {
			fwrite($fp, '<html><body><p><h1>' . $title . '</h1></p>');
			fwrite($fp, '<p>' . $text . '</p>');
			if($imgPath) {
				fwrite($fp, '<p><img src="' . $imgPath . '" /></p>');
			}
			else {
				fwrite($fp, '<p>No image uploaded</p>');
			}
			
			fwrite($fp, '<p><a href="http://demo.ilabs.no/test/widgets/vg/myposts.php">Mine poster</a></p>');
			fwrite($fp, '<p><a href="http://demo.ilabs.no/test/widgets/vg/blog.html">Ny post</a></p>');
			fwrite($fp, '</body></html>');
			fclose($fp);
			return 1;			
		}		
	}
	//print_r($_POST);
	$title	 = '';
	$body	 = '';
	$imgPath = '';
		
	if(isset($_POST["send"]) && $_POST["send"] == "Send") {
		unset($imagename);
			
		$title = $_POST['title']; 
		$body  = $_POST['text'];
	
		if(!isset($_FILES) && isset($HTTP_POST_FILES))
			$_FILES = $HTTP_POST_FILES;
	
		if(!isset($_FILES['image_file']))
			$error["image_file"] = "An image was not found.";
	
	
		$imagename = basename($_FILES['image_file']['name']);
		//echo $imagename;
	
		if(empty($imagename))
			$error["imagename"] = "The name of the image was not found.";
	
		if(empty($error)) {
			$newimage = "posts/" . $imagename;
			//echo $newimage;
			$result = @move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
				
			$imgPath = $newimage;  
			if(empty($result)) {
				$error["result"] = "There was an error moving the uploaded file.";
			}
		}
		$fileName = 'posts/' . createFileName($_SESSION['uid']);
		
		if(createBlogPost($fileName, $title, $body, $imagename) > 0 ) {
			$url = 'http://demo.ilabs.no/test/widgets/vg/' . $fileName; 
			//print  '<a href="' . $url . '">' . $url . '</a>'; 
			header('Location: ' . $url);
		}
		else {
			header('Location: http://demo.ilabs.no/test/widgets/vg/errorupload.html');
		}
		exit();
	}
?>